<?php
/**
 * Created By Leroi Liu
 * Email：675667823@qq.com
 * Date：2023/2/12
 * Description：
 **/

namespace MicroCyan\ThinkHelp\middleware;

class AllowCrossDomain
{
    public function handle($request, \Closure $next)
    {
        $cookieDomain = \think\facade\Config::get('cookie.domain','');
        $origin = $request->header('origin');
        if (!empty($origin)){
            header('Access-Control-Allow-Origin: '.$origin);
        }elseif (!empty($cookieDomain)){
            header('Access-Control-Allow-Origin: '.$cookieDomain);
        }else {
            header('Access-Control-Allow-Origin: *');
        }
        header('Access-Control-Max-Age: 1800');
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With, Token');
        if (strtoupper($request->method(true)) == 'OPTIONS') {
            exit(12);
        }
        return $next($request);
    }
}
